$(document).ready(function () {
    //全选组件
    $('[type="checkbox"]:first').click(function () {
        if(this.checked){
            $('[type="checkbox"]').prop("checked", true);
            $('[role="operate"]').removeClass('disabled');
        }else{
            $('[type="checkbox"]').prop("checked", false);
            $('[role="operate"]').addClass('disabled');
        }
    });
    $('[type="checkbox"]').not(":first").click(function () {
        if(this.checked) {
            if($('[type="checkbox"]').length-1==$('[type="checkbox"]:checked').length){
                $('[type="checkbox"]:first').prop("checked", true);
            }
            $('[role="operate"]').removeClass('disabled');

        }else{
            if ($('[type="checkbox"]:first:checked').length) {
                $('[type="checkbox"]:first').prop("checked", false);
            }
            if($('[type="checkbox"]:checked').length==0){
                $('[role="operate"]').addClass('disabled');
            }
        }
    });
    //pop弹窗组件
    $("tr[role='pop']").popover({
        trigger:'manual',
        placement : 'left',
        title : $(this).data('title'),
        html: 'true',
        content : $(this).data('content'),
        animation: false
    }).on("mouseenter", function () {
        var _this = this;
        $(this).popover("show");
        $(this).siblings(".popover").on("mouseleave", function () {
            $(_this).popover('hide');
        });
    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide")
            }
        }, 100);
    });
    //图片
    $("img[role='pop']").popover({
        trigger:'manual',
        placement : 'right',
        title : $(this).data('title'),
        html: 'true',
        content : $(this).data('content'),
        animation: false
    }).on("mouseenter", function () {
        var _this = this;
        $(this).popover("show");
        $(this).siblings(".popover").on("mouseleave", function () {
            $(_this).popover('hide');
        });
    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide")
            }
        }, 100);
    });
    //链接


    //复制连接
    $('[role="copylink"]').zclip({
        path:'../../public/admin/js/zclip/ZeroClipboard.swf',
        copy: function(){return $(this).data('link')},
        afterCopy:function(){
            toastTop('复制成功');
        }
    });
});
/**
 * Created by Root on 2016/12/6.
 */
function isPhone(phone) {
    if(!(/^1[34578]\d{9}$/.test(phone))){
        return false;
    }else {
        return true;
    }
}
function isEmail(str){
    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
    return reg.test(str);
}
//中间提示
function toastTop(message,type) {
    if(type==''){
        type=1;
    }
    var toast_div = '<div class="msgbox"><div class="msg msg-success">'+message+'</div></div>';
    if(type==2){
        var toast_div = '<div class="msgbox"><div class="msg msg-error">'+message+'</div></div>';
    }
    $('body .msgbox').remove();
    $('body').append(toast_div);
    setTimeout(function () {
        $('.msgbox').animate({
            top:'-32px',
            opacity:'0'
        },300);
    },1500);
}
//底部提示
function toastBottom(message,type) {
    if(type==''){
        type=1;
    }
    var toast_div = '<div class="msgboxbottom"><div class="msg msg-success">'+message+'</div></div>';
    if(type==2){
        var toast_div = '<div class="msgboxbottom"><div class="msg msg-error">'+message+'</div></div>';
    }
    $('body .msgbox').remove();
    $('body').append(toast_div);
    setTimeout(function () {
        $('.msgboxbottom').animate({
            bottom:'-32px',
            opacity:'0'
        },300);
    },1500);
}
//中间提示
function toastCenter(message,type,close) {
}
//时间插件
/*
* 用法手册
* dateInit('input[name="membertime"]','input[name="start_time"]','input[name="end_time"]');简单初始化
* is_single:是否是单时间窗口
* start_time:开始时间
* end_time:结束时间
* date_limit:日期限制
* ranges:自定义快捷方式
* is_time:是否开启时间选择
* opens:打开方向
* data={is_single:true,start_time:start_time,end_time:end_time,date_limit:date_limit,ranges:ranges,is_time:is_time,opens:opens}
* */
function dateInit(id,start_id,end_id,data){
    if(!data){
        data={};
    }
    var option = {
        "locale": {
            "direction": "ltr",
            "format": "YYYY-MM-DD HH:mm",
            "separator": " - ",
            "applyLabel": "确认",
            "cancelLabel": "取消",
            "fromLabel": "从",
            "toLabel": "到",
            "customRangeLabel": "自定义日期",
            "daysOfWeek": [
                "日",
                "一",
                "二",
                "三",
                "四",
                "五",
                "六"
            ],
            "monthNames": [
                "一月",
                "二月",
                "三月",
                "四月",
                "五月",
                "六月",
                "七月",
                "八月",
                "九月",
                "十月",
                "十一月",
                "十二月"
            ],
            "firstDay": 1
        },
        "autoApply": true
    };
    if(data.hasOwnProperty("start_time")){
        option.startDate=data.start_time;
    }
    if(data.hasOwnProperty("end_time")){
        option.endDate=data.end_time;
    }
    if(data.hasOwnProperty("date_limit")){
        option.dateLimit= {
            "days": data.date_limit
        }
    }
    if(data.hasOwnProperty("is_single")){
        option.singleDatePicker = data.is_single;
    }

    if(!data.hasOwnProperty("ranges")){
        data.ranges={
            "今天": [moment().startOf('day'), moment().endOf('day')],
            "昨天": [moment().subtract( 1, 'days').startOf('day'), moment().subtract(1,'days').endOf('day')],
            "近一周": [moment().subtract( 6,'days').startOf('day'), moment()],
            "近一月":[moment().subtract(29,'days').startOf('day'), moment()],
        };
    }
    option.ranges=data.ranges;

    if(!data.hasOwnProperty("opens")){
        data.opens='left';
    }
    option.opens=data.opens;

    if(data.hasOwnProperty("is_time")){
        option.timePicker=data.is_time;
        option.timePicker24Hour=data.is_time;
    }
    if(!id){
        console.log('初始化时间插件没有指定id');
        return false;
    }
    $(id).daterangepicker(option, function(start, end, label) {
        if(start_id!=''){
            $(start_id).val(start.format('YYYY-MM-DD HH:mm'));
        }
        if(end_id!=''){
            $(end_id).val(end.format('YYYY-MM-DD HH:mm'));
        }
    });
}

/*
* 图片上传控件
* 赵坤
* 20161214
*
* */
function imageUpload(id,token_url,domain_url,dragId,data) {
    if(id==''){
        console.log('未设置触发id')
    }
    if(token_url==''){
        console.log('未设置token_url');
        return;
    }
    if(domain_url==''){
        console.log('未设置domain_url');
        return;
    }
    if(dragId==''){
        console.log('未设置dragId');
        return;
    }
    var option = {
        runtimes: 'html5,flash,html4',      // 上传模式，依次退化
        browse_button: id,         // 上传选择的点选按钮，必需  'pickfiles'
        uptoken_url: token_url,         // Ajax请求uptoken的Url，强烈建议设置（服务端提供）
        get_new_uptoken: false,             // 设置上传文件的时候是否每次都重新获取新的uptoken
        // downtoken_url: '/downtoken',
        // Ajax请求downToken的Url，私有空间时使用，JS-SDK将向该地址POST文件的key和domain，服务端返回的JSON必须包含url字段，url值为该文件的下载地址
        unique_names: true,              // 默认false，key为文件名。若开启该选项，JS-SDK会为每个文件自动生成key（文件名）
        domain: domain_url,     // bucket域名，下载资源时用到，必需
        // container: 'container',             // 上传区域DOM ID，默认是browser_button的父元素
        max_file_size: '8mb',             // 最大文件体积限制
        flash_swf_url: 'https://cdn.staticfile.org/Plupload/2.1.1/Moxie.swf',  //引入flash，相对路径
        silverlight_xap_url : 'https://cdn.staticfile.org/Plupload/2.1.1/Moxie.xap',
        max_retries: 3,                     // 上传失败最大重试次数
        dragdrop: true,                     // 开启可拖曳上传
        drop_element: dragId,          // 拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '4mb',                  // 分块上传时，每块的体积
        filters: {
            mime_types : [
                {title : "Image files", extensions: "jpg,jpeg,gif,png"}
            ]
        },
        auto_start: true,                   // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
        init: {
            'UploadProgress': function(up, file) {
                // 每个文件上传时，处理相关的事情
            },
            'FileUploaded': function(up, file, info) {
                var domain = up.getOption('domain');
                // var res = parseJSON(info);
                // var sourceLink = domain +"/"+ res.key; 获取上传成功后的文件的Url
                console.log(info);
                console.log(file);
                var img_div = '<div class="col-lg-2 col-sm-2 water-up-2"><img data-value="'+file.target_name+'" src="http://'+domain_url+'/'+file.target_name+'" class="img-responsive">'+
                        '<a class="badge img-badge" onclick="water_delete_up_img(this);"><span class="fa fa-times"></span></a></div>';
                data.up.hide();
                data.uplist.show();
                data.uplist.prepend(img_div);
                // 每个文件上传成功后，处理相关的事情
                // 其中info是文件上传成功后，服务端返回的json，形式如：
                // {
                //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //    "key": "gogopher.jpg"
                //  }
                // 查看简单反馈

            },
            'Error': function(up, err, errTip) {
                //上传出错时，处理相关的事情

            },
            'UploadComplete': function() {
                //队列文件处理完毕后，处理相关的事情
            }
        }
    };
    if(data.hasOwnProperty('container')){
        option.container=data.container;
    }
    if(data.hasOwnProperty('multi_selection')){
        option.multi_selection=data.multi_selection;
    }
    return Qiniu.uploader(option);
}

jQuery.extend({
    isEmail: function(str) {
        return /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/.test($.trim(str));
    },
    isIDCard: function(obj) {
        var aCity = {11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙 江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖 北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西 藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国 外"};
        var iSum = 0;
        //var info = "";
        var strIDno = obj;
        var idCardLength = strIDno.length;
        if (!/^\d{17}(\d|x)$/i.test(strIDno) && !/^\d{15}$/i.test(strIDno))
            return false; //非法身份证号

        if (aCity[parseInt(strIDno.substr(0, 2))] == null)
            return false;// 非法地区

        // 15位身份证转换为18位
        if (idCardLength == 15)
        {
            sBirthday = "19" + strIDno.substr(6, 2) + "-" + Number(strIDno.substr(8, 2)) + "-" + Number(strIDno.substr(10, 2));
            var d = new Date(sBirthday.replace(/-/g, "/"))
            var dd = d.getFullYear().toString() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
            if (sBirthday != dd)
                return false; //非法生日
            strIDno = strIDno.substring(0, 6) + "19" + strIDno.substring(6, 15);
            strIDno = strIDno + GetVerifyBit(strIDno);
        }

        // 判断是否大于2078年，小于1900年
        var year = strIDno.substring(6, 10);
        if (year < 1900 || year > 2078)
            return false;//非法生日

        //18位身份证处理

        //在后面的运算中x相当于数字10,所以转换成a
        strIDno = strIDno.replace(/x$/i, "a");

        sBirthday = strIDno.substr(6, 4) + "-" + Number(strIDno.substr(10, 2)) + "-" + Number(strIDno.substr(12, 2));
        var d = new Date(sBirthday.replace(/-/g, "/"))
        if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()))
            return false; //非法生日
        // 身份证编码规范验证
        for (var i = 17; i >= 0; i --)
            iSum += (Math.pow(2, i) % 11) * parseInt(strIDno.charAt(17 - i), 11);
        if (iSum % 11 != 1)
            return false;// 非法身份证号

        // 判断是否屏蔽身份证
        var words = new Array();
        words = new Array("11111119111111111", "12121219121212121");

        for (var k = 0; k < words.length; k++) {
            if (strIDno.indexOf(words[k]) != -1) {
                return false;
            }
        }

        return true;


    },
    isUrl: function(str) {
        return /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($.trim(str));
    },
    isInt: function(str) {
        return  /^[-\+]?\d+$/.test($.trim(str));
    },
    isUserID: function(str) {
        return /^\s*[A-Za-z0-9_-]{6,20}\s*$/.test($.trim(str));
    },
    isMobile: function(str) {
        return $.trim(str) !== '' && /^1[3|4|5|7|8][0-9]\d{8}$/.test($.trim(str));
    },
    isChinese: function(str) {
        return $.trim(str) != '' & !/[^\u4e00-\u9fa5]/.test($.trim(str));
    },
    isEnglish:function(str){
        return $.trim(str) != '' & !/[^a-zA-Z]/.test($.trim(str));
    },
    isPassword: function(str) {
        return  /^[^\u4e00-\u9fa5\s]{6,20}$/.test($.trim(str));
    },
    isFloat: function(str) {
        return /^(\+|-)?\d+($|\.\d+$)/.test($.trim(str));
    },
    isNumber: function(str) {
        return !$.isEmpty(str) && !isNaN(str);
    },
    isIP: function(str) {
        if (/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.test($.trim(str))) {
            if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256)
                return true;
        }
        return false;
    },
    isDate: function(str) {
        var r = $.trim(str).split("-");
        if (r == null)
            return false;
        var d = new Date(r[0], r[1] - 1, r[2]);
        return (d.getFullYear() == r[0] && (d.getMonth() + 1) == r[1] && d.getDate() == r[2]);
    },
    htmlEncode: function(str) {
        str = str.replace(/&/g, '&amp;');
        str = str.replace(/</g, '&lt;');
        str = str.replace(/>/g, '&gt;');
        str = str.replace(/(?:\t| |\v|\r)*\n/g, '<br />');
        str = str.replace(/  /g, '&nbsp; ');
        str = str.replace(/\t/g, '&nbsp; &nbsp; ');
        str = str.replace(/\x22/g, '&quot;');
        str = str.replace(/\x27/g, '&#39;');
        return $.trim(str);
    },
    htmlDecode: function(str) {
        str = str.replace(/&amp;/gi, '&');
        str = str.replace(/&nbsp;/gi, ' ');
        str = str.replace(/&quot;/gi, '"');
        str = str.replace(/&#39;/g, "'");
        str = str.replace(/&lt;/gi, '<');
        str = str.replace(/&gt;/gi, '>');
        str = str.replace(/<br[^>]*>(?:(\r\n)|\r|\n)?/gi, '\n');
        return $.trim(str);
    },
    preview: function(str) {
        var testwin = open("");
        testwin.document.open();
        testwin.document.write(str);
        testwin.document.close();
    },
    isEmpty: function(str) {
        return $.trim(str) == '' || str == undefined
    },
    arrayIndexOf: function(arr, substr, start) {
        var ta, rt, d = '\0';
        if (start != null) {
            ta = arr.slice(start);
            rt = start;
        } else {
            ta = arr;
            rt = 0;
        }
        var str = d + ta.join(d) + d, t = str.indexOf(d + substr + d);
        if (t == -1)
            return -1;
        rt += str.slice(0, t).replace(/[^\0]/g, '').length;
        return rt;
    },
    arrayLastIndexOf: function(arr, substr, start) {
        var ta, rt, d = '\0';
        if (start != null) {
            ta = arr.slice(start);
            rt = start;
        } else {
            ta = arr;
            rt = 0;
        }
        ta = ta.reverse();
        var str = d + ta.join(d) + d, t = str.indexOf(d + substr + d);
        if (t == -1)
            return -1;
        rt += str.slice(t).replace(/[^\0]/g, '').length - 2;
        return rt;
    },
    arrayReplace: function(arr, reg, rpby) {
        var ta = arr.slice(0), d = '\0';
        var str = ta.join(d);
        str = str.replace(reg, rpby);
        return str.split(d);
    },
    arraySearch: function(arr, reg) {
        var ta = arr.slice(0), d = '\0', str = d + ta.join(d) + d, regstr = reg.toString();
        reg = new RegExp(regstr.replace(/\/((.|\n)+)\/.*/g, '\\0$1\\0'), regstr.slice(regstr.lastIndexOf('/') + 1));
        t = str.search(reg);
        if (t == -1)
            return -1;
        return str.slice(0, t).replace(/[^\0]/g, '').length;
    },
    nullundefined: function(str) {
    },
    setClipboard: function(maintext) {
        if (window.clipboardData) {
            window.clipboardData.setData("Text", maintext);
            alert("复制成功！");
        }
        else if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {
                alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将 'signed.applets.codebase_principal_support'设置为'true'");
                return;
            }
            var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
            if (!clip)
                return;
            var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
            if (!trans)
                return;
            trans.addDataFlavor('text/unicode');
            var str = new Object();
            var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
            var copytext = txt;
            str.data = copytext;
            trans.setTransferData("text/unicode", str, copytext.length * 2);
            var clipid = Components.interfaces.nsIClipboard;
            if (!clip)
                return false;
            clip.setData(trans, null, clipid.kGlobalClipboard);
            alert("复制成功！")
        }
    }
});

(function($) {
    $.fn.isInt = function() {
        return $.isInt($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isIDCard = function() {
        return $.isIDCard($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isEnglish = function() {
        return $.isEnglish($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isEmail = function() {
        return $.isEmail($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isDate = function() {
        return $.isDate($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isIP = function() {
        return $.isIP($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isChinese = function() {
        return $.isChinese($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isEmpty = function() {
        return $.isEmpty($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isUrl = function() {
        return $.isUrl($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isFloat = function() {
        return $.isFloat($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isNumber = function() {
        return $.isNumber($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isUserID = function() {
        return $.isUserID($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isPassword = function() {
        return $.isPassword($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.isMobile = function() {
        return $.isMobile($(this).val());
    }
})(jQuery);
(function($) {
    $.fn.len = function() {
        return $(this).val().length;
    }
})(jQuery);
(function($) {
    $.fn.checked = function() {

        return $(this).get(0).checked();
    }
})(jQuery);
(function($){

    $.fn.resizeImage = function(iwidth,iheight){

        var w = $(this).width() ;
        var h =  $(this).height() ;
        var _img = new Image();
        _img.src = $(this).attr("src");
        if(_img.width > _img.height)
        {
            h = (_img.height / _img.width) *w;
            w = (_img.width > iwidth) ? iwidth : _img.width;

        }
        else if(_img.width < _img.height)
        {
            w= (_img.width / _img.height) * h ;
            h= (_img.height > iheight) ? iheight : _img.height;

        }
        else
        {
            h = (_img.height > iheight) ? iheight : _img.height;
            w= (_img.width > iwidth) ? iwidth : _img.width;
        }
        $(this).css({width: w+ "px",height:h+"px"});
    }


})(jQuery);
(function($) {

    $.fn.breakWords = function(width) {
        var _this = $(this);
        var content = _this.html();

        if (content == undefined) {
            return;
        }
        if (content.length <= width) {
            _this.html(content);
        }
        else {
            var str = '';

            for (var i = 0; i < content.length; i++) {
                if (i % width != 0) {
                    str += content.substr(i, 1);

                }
                else {
                    if (i != 0) {
                        str += "<br/>" + content.substr(i, 1);
                    }
                }
            }

            _this.html(str);
        }

    }
})(jQuery);
(function($) {
    $.fn.limitWidth = function() {
        var _this = $(this);
        var elments = _this.getElementsByTagName("*");
        for (var i = 0; i < elments.length; i++) {
            if (parseInt(elments[i].getAttribute("width")) > width) {
                elments[i].setAttribute("width", width - 1);
            }
            if (elments[i].style.width) {
                if (parseInt(elments[i].style.width) > width) {
                    elments[i].style.width = width - 1;
                }
            }
        }
        return _this;
    }
})(jQuery);
(function($) {
    $.fn.limitLength = function(num, inputID,isInput) {

        var textarea = $(this);

        var input = null;
        if (inputID) {
            input = $("#" + inputID);
        }
        if (input) {
            isInput?input.val(num - textarea.len()):input.html(num - textarea.len());
        }
        function limit(textarea, num) {
            if (textarea.len() >= num) {
                textarea.val(textarea.val().substring(0, num));
            }
            else {
                if (input) {
                    isInput?input.val(num - textarea.len()):input.html(num - textarea.len());
                }
            }
        }
        textarea.keypress(function(e) {
            limit($(this), num);
        }).keyup(function(e) {
            limit($(this), num);
        }).mouseup(function(e) {
            limit($(this), num);
        });
        return textarea;
    }
})(jQuery);
(function($) {
    $.fn.nulldefined = function() {
    }
})(jQuery);